package com.github.yeecode.mybatisdemo;

import com.github.yeecode.mybatisdemo.dao.UserMapper;
import com.github.yeecode.mybatisdemo.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.defaults.DefaultSqlSession;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

public class DemoApplication {
    public static void main(String[] args) {
        // 第一阶段：MyBatis的初始化阶段
        String resource = "mybatis-config.xml";
        // 得到配置文件的输入流
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 得到SqlSessionFactory  实际上就是 DefaultSqlSessionFactory
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        DefaultSqlSessionFactory sqlSessionFactory = (DefaultSqlSessionFactory)sqlSessionFactoryBuilder.build(inputStream);

        // 第二阶段：数据读写阶段
        try (SqlSession session = (DefaultSqlSession) sqlSessionFactory.openSession()) {
            // 找到接口对应的实现  到后面直接 将整个包都装入 mybatis
            UserMapper userMapper = session.getMapper(UserMapper.class);
            // 组建查询参数
            User obj = new User();
            obj.setSchoolName("Sunny School");
            // 调用接口展开数据库操作
            List<User> userList =  userMapper.queryUserBySchoolName(obj);
            // 打印查询结果
            for (User user : userList) {
                System.out.println("user.toString() = " + user.toString());
            }
            //直接使用session 直接调用 就像 sqlId 一样
            List<Object> list = session.selectList("com.github.yeecode.mybatisdemo.dao.UserMapper.queryUserBySchoolNameMap", "Sunny School");
            System.out.println(list);
            if (list.get(1) instanceof  User){

                System.out.println("返回来的是 User ");
            }else{
                System.out.println(list.get(1).getClass());
                HashMap map = (HashMap) list.get(0);
                System.out.println(map.get("name"));

            }

        }
    }
}
